package cn.jbolt.ai.core.chain.node.action.dbquery;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.ai.app.service.AiAppService;
import cn.jbolt.ai.core.chain.ChainContext;
import cn.jbolt.ai.core.chain.node.action.funccall.FuncCallNodeProvider;
import cn.jbolt.ai.core.chain.node.action.intention.IntentionNodeConfig;
import cn.jbolt.ai.core.chain.node.base.AppConfigConstant;
import cn.jbolt.ai.core.chain.node.base.BaseNode;
import cn.jbolt.ai.core.chain.node.base.LlmConfig;
import cn.jbolt.ai.core.chain.node.provider.CommonNodeProvider;
import cn.jbolt.ai.core.chain.node.provider.IntentionNodeProvider;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.jboltai.capability.message.AIIntention;
import com.jboltai.capability.model.JBoltAI;
import com.jboltai.event.ai.aiintention.AIIntentionEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class DbQueryNodeProvider extends BaseNode implements CommonNodeProvider {
    private static final Logger logger = LoggerFactory.getLogger(DbQueryNodeProvider.class);


    @Override
    public void provide(JsonNode nodeConfig, ChainContext context) {
        DbQueryConfig dbQueryConfig = DbQueryConfig.from(nodeConfig.get(AppConfigConstant.CONFIG_TYPE_DB_QUERY));


        if (dbQueryConfig == null || StrUtil.isBlank(dbQueryConfig.getSql())) {
            throw new RuntimeException("未配置数据库查询语句");
        }
        if (dbQueryConfig.getSql().trim().toLowerCase().startsWith("select") == false) {
            throw new RuntimeException("查询语句不合法");
        }

        List<Map<String, Object>> maps = SqlRunner.db().selectList(dbQueryConfig.getSql());
        if (StrUtil.isNotBlank(dbQueryConfig.getOutputField())) {
            context.setAttr(dbQueryConfig.getOutputField(), maps);
        }

    }






}
